package com.example.wumeng.scangundemo.widget;

import android.content.Context;
import android.widget.Toast;

/**
 * 创建日期：2018/4/23 on 15:40
 * 描述:
 * 作者: WuMeng
 */
public class SingleToast {

    private static final Object SYNC_LOCK = new Object();

    private static Toast mToast;

    private static Context context; // 上下文

    private static Context getContext() {
        return context;
    }

    private static void setContext(Context context) {
        SingleToast.context = context;
    }

    /**
     * 获取Toast环境，利用单例模式加锁
     */
    private static void initToastInstance() {
        if (mToast == null) {
            synchronized (SYNC_LOCK) {
                if (mToast == null) {
                    mToast = Toast.makeText(context,"",Toast.LENGTH_SHORT);
                }
            }
        }
    }

    /**
     * 展示Toast
     * @param text 内容
     * @param context 环境
     */
    public static void showToast(String text,Context context) {
        setContext(context);
        if (getContext() != null && text != null) {
            initToastInstance();
            mToast.setDuration(Toast.LENGTH_SHORT);
            mToast.setText(text);
            mToast.show();
        }
    }

}
